package service;

import dao.OrderDao;
import dao.OrderDetailDao;
import entity.Address;
import entity.Cart;
import entity.Order;
import entity.OrderDetail;

import java.sql.SQLException;
import java.util.*;

public class OrderService {

    private OrderDao orderDao = new OrderDao();
    private OrderDetailDao orderDetailDao = new OrderDetailDao();
    private CartService cartService = new CartService();
    public void createOrder(int userId, List<Cart> cartItems, Address address, double totalPric) throws SQLException {
        String detailAddress = String.format(
                "%s %s %s %s %s",
                address.getPeiceName(),
                address.getPhone(),
                address.getProvince(),
                address.getDistrict(),
                address.getDetailAddress()
        );
        Map<Integer, List<Cart>> groupedByShopId = new HashMap<>();

        for (Cart cart : cartItems) {
            int shopId = cart.getShopId();
            if (!groupedByShopId.containsKey(shopId)) {
                groupedByShopId.put(shopId, new ArrayList<>());
            }
            groupedByShopId.get(shopId).add(cart);
        }

        Collection<List<Cart>> allValues = groupedByShopId.values();

        // 遍历所有的 List<Cart>,做到将不同店铺的商品分开生成不同的订单
        for (List<Cart> cartList : allValues) {
            Double totalPrice = 0.0;
            for (Cart cart : cartList) {
                totalPrice += cart.getPrice() * cart.getQuantity();
            }
            //运费
            totalPrice += 5;
            int orderId = orderDao.createOrder(userId, totalPrice,detailAddress);
            for (Cart cart : cartList) {
                orderDetailDao.createOrderDetail(orderId, cart.getProductId(), cart.getQuantity(), cart.getPrice());
            }
        }

        cartService.deleteAllItems(userId);
    }

    public List<Order> getOrdersByUserId(int userId) {
        return orderDao.getOrdersByUserId(userId);
    }
    public List<Order> getOrdersByShopUserId(int userId) {
        return orderDao.getOrdersByShopUserId(userId);
    }



    public boolean updateOrderStatus(int orderId,String status) {
        return orderDao.updateOrderStatus(orderId,status);
    }



    public List<OrderDetail> getOrderDetailsByOrderId(int orderId) {
        return orderDetailDao.getOrderDetailsByOrderId(orderId);
    }
}
